package cn.darkhorse.device.service.impl;

import cn.darkhorse.device.pojo.MesOilConsumeInfo;
import cn.darkhorse.device.mapper.MesOilConsumeInfoMapper;
import cn.darkhorse.device.service.MesOilConsumeInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 油耗记录 服务实现类
 * </p>
 *
 * @author yangtianqi
 * @since 2024-11-06
 */
@Service
public class MesOilConsumeInfoServiceImpl extends ServiceImpl<MesOilConsumeInfoMapper, MesOilConsumeInfo> implements MesOilConsumeInfoService {

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public MesOilConsumeInfo view(Long id) {
        return getById(id);
    }

    @Override
    public boolean saveConsumeInfo(MesOilConsumeInfo mesOilConsumeInfo) {
        if (mesOilConsumeInfo.getId()==null ) {
            Long count = lambdaQuery().eq(MesOilConsumeInfo::getCode, mesOilConsumeInfo.getCode()).count();
            if (count > 0) {
                throw new RuntimeException("编码不可重复");
            }
            mesOilConsumeInfo.setCreateBy(SecurityUtils.getUsername());
            mesOilConsumeInfo.setCreateTime(LocalDateTime.now());
        }else {
            Long count = lambdaQuery().eq(MesOilConsumeInfo::getCode, mesOilConsumeInfo.getCode()).ne(MesOilConsumeInfo::getId,mesOilConsumeInfo.getId()).count();
            if (count > 0) {
                throw new RuntimeException("编码不可重复");
            }
        }


        return saveOrUpdate(mesOilConsumeInfo);
    }

    @Override
    public List<MesOilConsumeInfo> list(MesOilConsumeInfo mesOilConsumeInfo) {
        LambdaQueryWrapper<MesOilConsumeInfo> wrapper = new LambdaQueryWrapper<>();
        if (mesOilConsumeInfo.getDeviceName()!=null){
            wrapper.like(MesOilConsumeInfo::getDeviceName,mesOilConsumeInfo.getDeviceName());
        }
        if (mesOilConsumeInfo.getDeviceCode()!=null){
            wrapper.like(MesOilConsumeInfo::getDeviceCode,mesOilConsumeInfo.getDeviceCode());
        }
        if (mesOilConsumeInfo.getRefuelTimeStart()!=null && mesOilConsumeInfo.getRefuelTimeEnd()!=null){
            LocalDate endTime = mesOilConsumeInfo.getRefuelTimeEnd();
            LocalDateTime localDateTime = LocalDateTime.of(endTime, LocalTime.MAX);
            wrapper.between(MesOilConsumeInfo::getRefuelTime,mesOilConsumeInfo.getRefuelTimeStart(),localDateTime);
        }
        wrapper.orderByDesc(MesOilConsumeInfo::getRefuelTime);

        return list(wrapper);
    }
}
